package com.steven.ourcontest.forum.view

import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.google.gson.JsonArray
import com.google.gson.JsonParser
import com.steven.ourcontest.R
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.forum.adapter.ForumDiscussAdapter
import com.steven.ourcontest.forum.viewmodel.ForumDiscussViewModel
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.me.widget.GlideRoundTransform
import com.steven.ourcontest.net.NetConstants
import com.steven.ourcontest.utils.DensityUtil
import com.steven.ourcontest.utils.ScreenUtils
import com.steven.ourcontest.utils.toast
import com.steven.ourcontest.widget.EnlargeImageDialog
import kotlinx.android.synthetic.main.activity_forum_discuss.*

class ForumDiscussActivity : BaseActivity() {
    private val adapter by lazy {
        ForumDiscussAdapter(this)
    }
    var fid: Long = 0
    private val forumDiscussViewModel: ForumDiscussViewModel by viewModels()
    private val imageViewList by lazy {
        ArrayList<ImageView>()
    }

    override fun getStatusBarColor(): Int {
        return R.color.main
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initListener()
    }

    override fun getViewId(): Int? {
        return R.layout.activity_forum_discuss
    }

    override fun initView() {

        recycler_discuss?.adapter = adapter

        fid = intent.getLongExtra("fid", 0)
        if (fid > 0) {
            forumDiscussViewModel.queryForumByFid(fid, {
            }, {
                toast(it.message.toString())
            })
            forumDiscussViewModel.queryDiscussList(fid, {
            }, {
                toast(it.message.toString())
            })
        }
    }

    private fun initListener() {
        iv_back?.setOnClickListener {
            finish()
        }
        tv_confirm?.setOnClickListener {
            if (!LoginController.isLogin){
                toast("请先登录")
                return@setOnClickListener
            }
            if (LoginController.userType == "") {
                toast("该账户尚未通过身份认证，如已提交请耐心等待~")
                return@setOnClickListener
            }
            val content = et_discuss?.text?.toString() ?: return@setOnClickListener
            if (content.isEmpty()) {
                return@setOnClickListener
            }
            forumDiscussViewModel.addDiscuss(fid, content)
        }
        forumDiscussViewModel.forumInfo.observe(this, Observer {
            if (it?.msg == "success") {
                it.info.let { info ->
                    tv_name?.text = info.uname
                    tv_forum_title.text = info.title
                    tv_content?.text = info.content
                    info.images?.let { images ->
                        val parser = JsonParser()
                        val jsonArray: JsonArray = parser.parse(images).asJsonArray
                        flex_container?.isVisible = jsonArray.size() > 0
                        jsonArray.forEach { JsonElement ->
                            val imageView = ImageView(this)
                            val layoutParams = LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.WRAP_CONTENT,
                                LinearLayout.LayoutParams.WRAP_CONTENT
                            )
                            DensityUtil.dp2px(this, 24f).let { dp ->
                                layoutParams.width = (ScreenUtils.getScreenWidth(this) - dp) / 3 - dp / 3
                                layoutParams.height = layoutParams.width
                                layoutParams.marginStart = dp / 6
                                layoutParams.marginEnd = dp / 6
                                layoutParams.topMargin = dp / 6
                                layoutParams.bottomMargin = dp / 6
                            }
                            imageView.layoutParams = layoutParams
                            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                            flex_container?.addView(imageView)
                            imageView.setOnClickListener {
                                EnlargeImageDialog(this).setUrl(JsonElement.asString).show()
                            }
                            Glide.with(this)
                                .load(NetConstants.ICON_BASE_URL + JsonElement.asString)
                                .placeholder(R.drawable.ic_placeholder)
                                .dontAnimate()
                                .error(R.drawable.aio_image_fail)
                                .into(imageView)
                            imageViewList.add(imageView)
                        }
                    }
                }
                Glide.with(this)
                    .load(NetConstants.ICON_BASE_URL + it.url.realIconUrl)
                    .placeholder(R.drawable.ic_placeholder)
                    .dontAnimate()
                    .error(R.drawable.aio_image_fail)
                    .apply(
                        RequestOptions.bitmapTransform(
                            GlideRoundTransform(
                                this,
                                10
                            )
                        )
                    )
                    .into(iv_icon)
            } else {
                toast(it?.msg.toString())
            }
        })
        forumDiscussViewModel.discussInfoList.observe(this, Observer {
            if (it?.msg == "success") {
                adapter.listData.clear()
                it.list.let { it1 ->
                    adapter.listData.addAll(it1)
                }
                adapter.notifyDataSetChanged()
            } else {
                toast(it?.msg.toString())
            }
        })
        forumDiscussViewModel.addDiscussRes.observe(this, Observer {
            if (it?.msg == "success") {
                forumDiscussViewModel.queryDiscussList(fid, {
                    et_discuss?.setText("")
                }, {})
            } else {
                toast(it?.msg.toString())
            }
        })
    }

    override fun onStart() {
        super.onStart()
        forumDiscussViewModel.addHistory(fid)
    }

    override fun onStop() {
        super.onStop()
        finish()
    }
}